package com.warmheart.controller.access;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.warmheart.base.annotation.AddOperateLog;
import com.warmheart.base.config.WhTransactionalControl;
import com.warmheart.base.session.SessionLocalUtils;
import com.warmheart.core.enums.OperationType;
import com.warmheart.entity.access.AccessPermission;
import com.warmheart.entity.user.UserRole;
import com.warmheart.entity.user.UserRoleMap;
import com.warmheart.impl.access.AccessRequestService;
import com.warmheart.impl.user.UserRoleMapService;
import com.warmheart.impl.user.UserRoleService;
import com.warmheart.service.access.IAccessPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.access.AccessRequest;
import com.warmheart.service.access.IAccessRequestService;

/**
 * 
 * @ClassName: AccessRequestController
 * @Description: 权限申请控制器
 * @author ZhangJianyang
 * @date 2025年06月16日 下午13:05:35
 *
 */
@RestController
@RequestMapping("/access/accessRequest")
public class AccessRequestController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AccessRequestController.class);

    // 注入权限申请service
    @Autowired(required = false)
    private IAccessRequestService accessRequestService;

    @Autowired(required = false)
    private IAccessPermissionService accessPermissionService;

    @Autowired(required = false)
    private UserRoleMapService userRoleMapService;

    @Autowired(required = false)
    private UserRoleService userRoleService;

//    @Auth(verifyLogin = true)
//    @RequestMapping("/checkPermission")
//    public CommonResult<Map<String, Object>> checkPermission(HttpServletRequest request, HttpServletResponse response){
//        //获取当前登录用户
//        Integer adminId = SessionLocalUtils.getOperator().getLoginUser().getUserId();
//        //获取当前用户角色
//        UserRoleMap userRoleMap=new UserRoleMap();
//        userRoleMap.coBuilder().userId().eq(adminId);
//        UserRoleMap userRoleMap1 = userRoleMapService.selectOne(userRoleMap);
//        if(userRoleMap1==null){
//            return CommonResult.failed(ResultCode.FAILED, "用户角色关联表中没有此用户");
//        }
//        Integer roleId = userRoleMap1.getRoleId();
//        if(roleId==null){
//            return CommonResult.failed(ResultCode.FAILED, "角色id为空");
//        }
//        //获取当前用户身份名称
//        UserRole userRole=new UserRole();
//        userRole.coBuilder().id().eq(roleId);
//        UserRole userRole1 = userRoleService.selectOne(userRole);
//        if(userRole1==null){
//            return CommonResult.failed(ResultCode.FAILED, "角色表中没有此角色");
//        }
//        String name = userRole1.getName();
//        if(StringUtils.isBlank(name)){
//            return CommonResult.failed(ResultCode.FAILED, "角色名称为空");
//        }
//        if(name.equals("系统管理员")||name.equals("安全管理员")){
//            return CommonResult.success("权限验证成功");
//        }
//        return CommonResult.failed(ResultCode.FAILED, "你不是管理员或管理员，没有权限");
//    }

    /**
     * 
     * @Title: listData
     * @Description: 查询权限申请列表数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.QUERY)
    @Auth(verifyLogin = true)
    @GetMapping("/listDataByCondition")
    public CommonResult<Map<String, Object>> listDataByCondition(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 参数对象
        AccessRequest accessRequest = new AccessRequest();

        // 申请人ID
        Integer applicantId = ParamMapUtil.getInteger(jsonMap, "applicantId");
        if (applicantId != null) {
            accessRequest.setApplicantId(applicantId);
        }

        // 资源类型
        String resourceType = ParamMapUtil.getString(jsonMap, "resourceType");
        if (StringUtils.isNotBlank(resourceType)) {
            accessRequest.setResourceType(resourceType);
        }

        // 资源ID
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            accessRequest.setResourceId(resourceId);
        }

        // 访问类型
        String accessType = ParamMapUtil.getString(jsonMap, "accessType");
        if (StringUtils.isNotBlank(accessType)) {
            accessRequest.setAccessType(accessType);
        }

        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        accessRequest.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        accessRequest.setPageId(pageId);

        // 查询列表
        PageInfo<AccessRequest> pageInfo = this.accessRequestService.queryByList(accessRequest);

        List<AccessRequest> dataList = pageInfo.getData();
        Map<String, Object> pageMap = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {

            // 整理返回数据
            for (AccessRequest tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("applicantId", tempData.getApplicantId());
                tempMap.put("resourceType", tempData.getResourceType());
                tempMap.put("resourceId", tempData.getResourceId());
                tempMap.put("accessType", tempData.getAccessType());
                tempMap.put("reason", tempData.getReason());
                tempMap.put("state", tempData.getState());
                tempMap.put("reviewComment", tempData.getReviewComment());
                tempMap.put("expiresTime", tempData.getExpiresTime());
                tempMap.put("createBy",tempData.getCreateBy());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询权限申请数据成功", resultMap);
    }

    /**
     * 
     * @Title: update
     * @Description: 修改权限申请数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.QUERY)
    @Auth(verifyLogin = true)
    @GetMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该权限申请ID不可为空");
        }

        // 校验是否存在
        AccessRequest checkAccessRequest = accessRequestService.queryById(id);
        if (checkAccessRequest == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该权限申请不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkAccessRequest.getId());
        tempMap.put("applicantId", checkAccessRequest.getApplicantId());
        tempMap.put("resourceType", checkAccessRequest.getResourceType());
        tempMap.put("resourceId", checkAccessRequest.getResourceId());
        tempMap.put("accessType", checkAccessRequest.getAccessType());
        tempMap.put("reason", checkAccessRequest.getReason());
        tempMap.put("state", checkAccessRequest.getState());
        tempMap.put("reviewComment", checkAccessRequest.getReviewComment());
        tempMap.put("expiresTime", checkAccessRequest.getExpiresTime());
        tempMap.put("createBy", checkAccessRequest.getCreateBy());
        tempMap.put("cstCreate", checkAccessRequest.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取权限申请数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存权限申请数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @WhTransactionalControl
    @AddOperateLog(addLog = true,value = OperationType.INSERT)
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PutMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 数据对象
        AccessRequest accessRequest = new AccessRequest();

        // 申请人ID
        Integer applicantId = ParamMapUtil.getInteger(jsonMap, "applicantId");
        if (applicantId != null) {
            accessRequest.setApplicantId(applicantId);
        }

        // 资源类型
        String resourceType = ParamMapUtil.getString(jsonMap, "resourceType");
        if (StringUtils.isNotBlank(resourceType)) {
            accessRequest.setResourceType(resourceType);
        }

        // 资源ID
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            accessRequest.setResourceId(resourceId);
        }

        // 访问类型
        String accessType = ParamMapUtil.getString(jsonMap, "accessType");
        if (StringUtils.isNotBlank(accessType)) {
            accessRequest.setAccessType(accessType);
        }

        //判断是否重复申请
        AccessRequest accessRequest1 = accessRequestService.selectOne(accessRequest);
        if(accessRequest1 != null) {
            return CommonResult.failed(ResultCode.FAILED, "请不要重复申请");
        }

        // 申请理由
        String reason = ParamMapUtil.getString(jsonMap, "reason");
        if (StringUtils.isNotBlank(reason)) {
            accessRequest.setReason(reason);
        }

        // 审批状态
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            accessRequest.setState(state);
        }
        else{
            accessRequest.setState("02");
        }

        // 审批意见
        String reviewComment = ParamMapUtil.getString(jsonMap, "reviewComment");
        if (StringUtils.isNotBlank(reviewComment)) {
            accessRequest.setReviewComment(reviewComment);
        }

        // 过期时间
        String expiresTime = ParamMapUtil.getString(jsonMap, "expiresTime");
        if (StringUtils.isNotBlank(expiresTime)) {

            // 过期时间
            Date expiresTimeRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(expiresTime);
            accessRequest.setExpiresTime(expiresTimeRealValue);
        }

        try {
            OperatorUtil.addOper(accessRequest);
            accessRequestService.add(accessRequest);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加权限申请失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加权限申请失败");
        }

        return CommonResult.success("添加权限申请成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存权限申请数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @WhTransactionalControl
    @AddOperateLog(addLog = true,value = OperationType.UPDATE)
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PostMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该权限申请ID不可为空");
        }

        // 是否存在校验
        AccessRequest checkAccessRequest = accessRequestService.queryById(id);
        if (checkAccessRequest == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该权限申请不存在");
        }

        // 申请人ID
        Integer applicantId = ParamMapUtil.getInteger(jsonMap, "applicantId");
        if (applicantId != null) {
            checkAccessRequest.setApplicantId(applicantId);
        }

        // 资源类型
        String resourceType = ParamMapUtil.getString(jsonMap, "resourceType");
        if (StringUtils.isNotBlank(resourceType)) {
            checkAccessRequest.setResourceType(resourceType);
        }

        // 资源ID
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            checkAccessRequest.setResourceId(resourceId);
        }

        // 访问类型
        String accessType = ParamMapUtil.getString(jsonMap, "accessType");
        if (StringUtils.isNotBlank(accessType)) {
            checkAccessRequest.setAccessType(accessType);
        }

        // 申请理由
        String reason = ParamMapUtil.getString(jsonMap, "reason");
        if (StringUtils.isNotBlank(reason)) {
            checkAccessRequest.setReason(reason);
        }

        // 审批状态
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            checkAccessRequest.setState(state);
        }

        // 审批意见
        String reviewComment = ParamMapUtil.getString(jsonMap, "reviewComment");
        if (StringUtils.isNotBlank(reviewComment)) {
            checkAccessRequest.setReviewComment(reviewComment);
        }

        // 过期时间
        String expiresTime = ParamMapUtil.getString(jsonMap, "expiresTime");
        if (StringUtils.isNotBlank(expiresTime)) {

            // 过期时间
            Date expiresTimeRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(expiresTime);
            checkAccessRequest.setExpiresTime(expiresTimeRealValue);
        }

        try {
            OperatorUtil.updateOper(checkAccessRequest);
            accessRequestService.updateIncludeAll(checkAccessRequest);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改权限申请失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改权限申请失败");
        }

        return CommonResult.success("修改权限申请成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除权限申请数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.DELETE)
    @Auth(verifyLogin = true)
    @DeleteMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该权限申请ID不可为空");
        }

        // 是否存在校验
        AccessRequest checkAccessRequest = accessRequestService.queryById(id);
        if (checkAccessRequest == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该权限申请不存在");
        }

        try {
            accessRequestService.deleteById(checkAccessRequest.getId());
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除权限申请失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除权限申请失败");
        }

        return CommonResult.success("删除权限申请成功");
    }

    //批量删除
    @Auth(verifyLogin = true)
    @DeleteMapping("/deleteBatch")
    public CommonResult<Map<String, Object>> deleteBatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        List<Integer> ids = ParamMapUtil.getIntegerList(jsonMap, "ids");
        if (ids == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该批准记录ID不可为空");
        }
        List<AccessRequest> accessRequests = accessRequestService.queryByIdList(ids);
        if (accessRequests == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该批准记录不存在");
        }
        try {
            accessRequestService.deleteByIdList(ids);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除批准记录失败");
        }

        return CommonResult.success("删除批准记录成功");
    }


    @AddOperateLog(addLog = true,value = OperationType.UPDATE)
    @Auth(verifyLogin = true)
    @PostMapping("/approvePermission")
    public CommonResult<Map<String, Object>> approvePermission(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该权限申请ID不可为空");
        }

        // 是否存在校验
        AccessRequest checkAccessRequest = accessRequestService.queryById(id);
        if (checkAccessRequest == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该权限申请不存在");
        }

        checkAccessRequest.setState("01");

        try {
            accessRequestService.updateIncludeAll(checkAccessRequest);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("审批通过失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "审批通过失败");
        }

        return CommonResult.success("审批通过成功");
    }



    @AddOperateLog(addLog = true,value = OperationType.INSERT)
    @Auth(verifyLogin = true)
    @PutMapping("/requestToPermission")
    public CommonResult<Map<String, Object>> requestToPermission(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        AccessRequest accessRequest=new AccessRequest();
        accessRequest.coBuilder().state().eq("01");
        List<AccessRequest> accessRequests = accessRequestService.selectList(accessRequest);

        for(AccessRequest accessRequest1: accessRequests) {
            AccessPermission accessPermission=new AccessPermission();
            accessPermission.setUserId(accessRequest1.getApplicantId());
            accessPermission.setResourceType(accessRequest1.getResourceType());
            accessPermission.setResourceId(accessRequest1.getResourceId());
            accessPermission.setAccessType(accessRequest1.getAccessType());
            accessPermission.setState(accessRequest1.getState());
            accessPermission.setSourceRequestId(accessRequest1.getApplicantId());
            accessPermission.setExpiresTime(accessRequest1.getExpiresTime());
            accessPermission.setCreateBy(SessionLocalUtils.getOperator().getLoginUser().getUserId());
            OperatorUtil.addOper(accessPermission);
            accessPermissionService.add(accessPermission);
            accessRequestService.deleteBySelective(accessRequest1);
        }


        return CommonResult.success("该申请添加到权限表成功");
    }
}
